<template>
  <div style="float: left;margin-top: 5px">
    <el-form ref="roleSearchRef" :model="searchFormData">
      <el-form-item label="关键词" >
        <el-input  type="text" v-model="searchFormData.name"></el-input>
      </el-form-item>
    </el-form>
  </div>
  <div style="height: 40px;margin-top: 5px;float: left;margin-left: 20px;">
    <el-button @click="searchDicClick">查询</el-button>
    <el-button @click="resetSearchClick">重置</el-button>
    <el-button v-check-permission="'system:org:add'" @click="addDicClick">新增</el-button>
  </div>
  <div style="clear: both"></div>
  <div style="height: calc(100% - 60px);">
    <Table  :show-page="false" ref="tableRef" :show-line-number="true"
            :showCheckBox="false" :url="orgUlr" :columns="columns" :table-model="TableModel.TREE" :tree-config="treeModelConfig">
      <template  v-slot:handle="slotProps">
        <el-button v-check-permission="'system:org:update'" @click.stop="editTableData(slotProps.rowData,slotProps.rowIndex)">编辑</el-button>
        <el-button v-check-permission="'system:org:delete'" @click.stop="deleteTableRowData(slotProps.rowData,slotProps.rowIndex)">删除</el-button>
      </template>
    </Table>
    <DialogForm ref="orgEditFormRef" :form="orgForm" title="编辑机构" @validateSuccess="validateSuccess">
      <template v-slot:permissionTree="slotProps">
        <Tree ref="selectTree" :tree-data="menuTreeData" :checked-model="checkedModel" :options="menuTreeOptions" :data-config="dataConfig">
        </Tree>
      </template>
      <template v-slot:orgTree="slotProps">
        <Tree ref="pSelectTree" :tree-data="orgTreeData" :checked-model="CheckedModel.SINGLE" :options="orgTreeOptions" :data-config="orgDataConfig"
          :checked-change="pCheckedChange">
        </Tree>
      </template>
    </DialogForm>
  </div>
</template>

<script setup >

import {inject, reactive, ref, toRaw} from "vue";
import Table from "@/components/plugs/table/Table.vue";
import {FormItemType} from "@/components/plugs/form/DialogFormInterface.js";
import Tree from "@/components/plugs/tree/Tree.vue";
import DialogForm from "@/components/plugs/form/DialogForm.vue";
import {CheckedModel} from "@/components/plugs/tree/TreeView.js";
import {AXIOS_NAME} from "@/constant/constant.js";
import {ElMessage} from "element-plus";
import {deleteRow, HandleEnum} from "@/utils/utils.ts";
import {TableModel} from "@/components/plugs/table/TableInterface.js";

const pSelectTree = ref(null);
const $axios = inject(AXIOS_NAME);
const selectTree = ref(null);
const tableRef = ref(null);
const orgEditFormRef = ref(null);
let menuTreeData = reactive([]);
let orgTreeData = reactive([]);
const roleSearchRef = ref(null);
const checkedModel = ref(CheckedModel.CASCADE);
const orgCheckedModel = ref(CheckedModel.SINGLE);
const orgUlr=  ref("/org/getOrgPage")

const searchFormData =  reactive({
  "name":""
});

let treeModelConfig = {
  idField:"id",
  pIdField:"pId",
  rootId:"0",
  expand:true
}

const menuTreeOptions = {
  "label": 'name'
}

const orgTreeOptions = {
  "label": 'name'
}

const dataConfig = {
  simple: true,
  pFiled:'pid',
  idField: 'id',
  rootId: '0'
};

const orgDataConfig = {
  simple: true,
  pFiled:'pId',
  idField: 'id',
  rootId: '0'
};
const columns = [
  {field:"name","desc": "名称"},
  {field:"description","desc": "描述"},
  {field:"showTime","desc": "创建时间",width: 200},
  {field:"handle","desc": "操作",isSlot:true,width:200}
];

let items = [];
items.push({type: FormItemType.INPUT_HIDDEN,label: 'id',name: 'id'});
items.push({type: FormItemType.INPUT_TEXT,label: '名称',name: 'name'});
items.push({type: FormItemType.INPUT_TEXT,label: '描述',name: 'description'});
items.push({type: FormItemType.SLOT,label: '父级',name:'orgTree'});
items.push({type: FormItemType.SLOT,label: '权限',name:'permissionTree'});

let orgForm = reactive({
  splitCol: 1,
  gutter: 20,
  labelWidth: 115,
  items:items,
  rules:{
    name: [
      { required: true, message: '请填写名称', trigger: 'blur' }
    ]
  },
});

const searchDicClick = () =>{
  tableRef.value.reload(toRaw(searchFormData));
}

const resetSearchClick = () =>{
  searchFormData.name = '';
}

const addDicClick = () =>{
  getMenuTreeData();
  orgEditFormRef.value.show();
}

const validateSuccess = (data) =>{
  const checked = selectTree.value.getCheckedKeys();
  data.string1 = checked.join(",");
  const pChecked  = pSelectTree.value.getCheckedKeys();
  data.pId =  pChecked.length <= 0 ? '0' : pChecked[0];
  $axios.post("/org/addOrUpdate",data).then(response => {
      const data = response.data;
      ElMessage.info(data.msg);
      if(data.code == 1){
        tableRef.value.reload();
        orgEditFormRef.value.close();
      }
  },error =>{

  });
}

const editTableData = (rowData,rowIndex) =>{
  getMenuTreeData();
  orgEditFormRef.value.show();
  orgEditFormRef.value.setData(rowData);
  $axios.post("/org/getPermissionsByOrgId",{"id":rowData.id}).then(response =>{
    const data = response.data.data;
    let checkedArr = [];
    data.forEach(item => {
      checkedArr.push(item.id);
    });
    selectTree.value.setCheckedKeys(checkedArr);
    pSelectTree.value.setCheckedKeys([rowData.pId]);
  });
}

const deleteTableRowData = (rowData,rowIndex) =>{
  deleteRow('/org/deleteOrg',rowData,function (state,data){
    if(state == HandleEnum.SUCCESS){
      tableRef.value.reload();
    }
  });
}

const getMenuTreeData = () =>{
  menuTreeData.clear();
  orgTreeData.clear();
  $axios.post('/menu/getAllPermissionTree').then((response) => {
    const data = response.data;
    if(data.code = 1){
      let permissionData = data.data;
      menuTreeData.pushAll(permissionData);
    }
  },(error) => {
  });

  $axios.post('/org/getAllOrg').then((response) => {
    const data = response.data;
    if(data.code = 1){
      let orgData = data.data;
      orgTreeData.pushAll(orgData);
    }
  },(error) => {
  });
}
getMenuTreeData();

const pCheckedChange = (node,checked,allCheckedData) => {
  const data = orgEditFormRef.value.getFormData();
  if(allCheckedData.length <= 0){
    return
  }
  if(data.id == allCheckedData[0].id){
    ElMessage.error("不能选择自身为父节点!");
    pSelectTree.value.setCheckedKeys([]);
  }
}

</script>

<style scoped>

</style>